﻿using AntdUI;
using Microsoft.VisualBasic.ApplicationServices;
using Super.Admin.Entities;
using Super.Admin.Global;
using Super.Admin.IServices;
using Super.Admin.Mappers;
using Super.Admin.Models.Department;
using Super.Admin.Models.Department;
using Super.Admin.Models.Role;
using Super.Admin.Models.User;
using Super.Admin.Services;
using Super.Admin.Utils;
using Super.Admin.Utils.ThemeManager;
using Super.Admin.Views.Base;
using Super.Admin.Views.Main;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ListView;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace Super.Admin.Views.Page
{
    public partial class DepartmentManagementView : BaseUserControl
    {
        private readonly IDepartmentService _departmentService;
        private readonly IUserOperateLogService _userOperateLogService;
        private readonly IUserService _userService;
        private List<CellButton> _cellButtons = new List<CellButton>();

        private List<DepartmentDetailModel> _allDepartments = new List<DepartmentDetailModel>();
        private List<DepartmentDetailModel> _departmentModels = new List<DepartmentDetailModel>();
        private List<UserBaseModel> _userModels = new List<UserBaseModel>();

        private bool _isLoad = false;
        public DepartmentManagementView(IDepartmentService departmentService, IUserOperateLogService userOperateLogService, IUserService userService)
        {
            InitializeComponent();
            InitializeAuthPermissionList();
            this.Load += DepartmentManagementView_Load; ;
            _departmentService = departmentService;
            _userOperateLogService = userOperateLogService;
            _userService = userService;
        }

        private void DepartmentManagementView_Load(object? sender, EventArgs e)
        {
            LoadDepartmentModels();
            LoadUserModels();

            TableDepartmentModel.Columns = new AntdUI.ColumnCollection
            {
                new AntdUI.Column("Id","部门ID",ColumnAlign.Center){ Width = "150",KeyTree = nameof(DepartmentDetailModel.Children)},
                new AntdUI.Column("Name","部门名称",ColumnAlign.Center){ Width = "150"},
                new AntdUI.Column("PersonInChargeName","负责人",ColumnAlign.Center){ Width = "120"},
                new AntdUI.Column("IsActiveTag","状态",ColumnAlign.Center){ Width = "100"},
                new AntdUI.Column("CreateTime","创建时间",ColumnAlign.Center){ Width = "220"},
                new AntdUI.Column("Remark","备注",ColumnAlign.Center){ Width = "450"},
                new AntdUI.Column("Operates","操作",ColumnAlign.Center){ColAlign = ColumnAlign.Center},
            };

        }

        private void InitializeAuthPermissionList()
        {
            BtnCreate.Visible = Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.DepartmentCreate);
            
            // 单元格按钮
            _cellButtons.Clear();
            if (Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.DepartmentCreateChild))
            {
                _cellButtons.Add(new CellButton(PermissionKeys.DepartmentCreateChild, "新增子部门", TTypeMini.Primary) { });
            }
            if (Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.DepartmentUpdate))
            {
                _cellButtons.Add(new CellButton(PermissionKeys.DepartmentUpdate, "编辑", TTypeMini.Primary) { });
            }
            if (Global.AppContext.Instance.AuthPermissionList.Contains(PermissionKeys.DepartmentDelete))
            {
                _cellButtons.Add(new CellButton(PermissionKeys.DepartmentDelete, "删除", TTypeMini.Error) { });
            }
        }

        private void LoadUserModels()
        {
            _userModels = (List<UserBaseModel>)_userService.GetUsers().ToBaseModels();
        }

        public override void DoRefresh()
        {
            LoadDepartmentModels();
        }

        private void LoadDepartmentModels()
        {
            List<DepartmentEntity> menuEntityList = (List<DepartmentEntity>)_departmentService.GetDepartments();
            _allDepartments = (List<DepartmentDetailModel>)menuEntityList.ToDetailModels();
            foreach (DepartmentDetailModel model in _allDepartments)
            {
                // 按钮
                model.Operates = TableHelper.CopyCellButton(_cellButtons).ToArray();
            }
            _departmentModels = SetDepartmentList(_allDepartments, 0);
            TableDepartmentModel.DataSource = _departmentModels;
        }

        public List<DepartmentDetailModel> SetDepartmentList(List<DepartmentDetailModel> sourceModel, int parent = 0)
        {
            List<DepartmentDetailModel> DepartmentModels = new List<DepartmentDetailModel>();
            List<DepartmentDetailModel> list = sourceModel.Where(s => s.ParentId == parent).ToList();
            foreach (var l in list)
            {
                DepartmentModels.Add(l);
                foreach (var dep in DepartmentModels)
                {
                    dep.Children = GetChildren(sourceModel, dep.Id).ToArray();
                    dep.DepartmentChild = GetChildren(sourceModel, dep.Id);
                }
            }
            return DepartmentModels;
        }
        private List<DepartmentDetailModel> GetChildren(List<DepartmentDetailModel> sourceModel, int parentId)
        {
            var children = sourceModel.Where(m => m.ParentId == parentId).ToList();
            foreach (var child in children)
            {
                child.Children = GetChildren(sourceModel, child.Id).ToArray();
                child.DepartmentChild = GetChildren(sourceModel, child.Id);
            }
            return new List<DepartmentDetailModel>(children);
        }
        private void BtnCreate_Click(object sender, EventArgs e)
        {
            DepartmentDetailModel model = new DepartmentDetailModel();
            var modifyView = new DepartmentManagementModify(ParentForm, _departmentModels, _allDepartments, _userModels, model, "新增部门");
            AntdUI.Modal.open(new Modal.Config(ParentForm, modifyView)
            {
                OnOk = ok =>
                {
                    if (string.IsNullOrEmpty(model.Name))
                    {
                        AntdUI.Message.error(ParentForm, "名称不能为空");
                        return false;
                    }
                    // 目录卡控
                    if (!DetermineTheParent(model, out string message))
                    {
                        AntdUI.Message.error(ParentForm, message);
                        return false;
                    }
                    _departmentService.CreateDepartment(model.ToEntity());
                    AntdUI.Message.success(ParentForm, "添加成功");
                    DoRefresh();
                    return true;
                }
            });
        }

        private void TableDepartmentModel_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            if (e.Record is DepartmentDetailModel model)
            {
                if (e.Btn.Id == PermissionKeys.DepartmentDelete)
                {
                    var result = AntdUI.Modal.open(new AntdUI.Modal.Config(ParentForm, "是否删除", new AntdUI.Modal.TextLine[]
                    {
                        new Modal.TextLine($"确认删除【[{model.Id}]{model.Name}】以及下面的子菜单吗",AntdUI.Style.Db.Primary),
                    }, AntdUI.TType.Error)
                    {
                        CancelText = "取消",
                        OkType = TTypeMini.Error,
                        OkText = "删除"
                    });
                    if (result == DialogResult.OK)
                    {
                        _departmentService.DeleteDepartment(model.Id);
                        _userOperateLogService.CreateUserOperateLog(Global.AppContext.Instance.LoginUserModel.UserId, $"部门管理删除：【[{model.Id}]{model.Name}】", PermissionKeys.DepartmentDelete);
                        AntdUI.Message.success(ParentForm, "删除成功");
                        DoRefresh();
                    }
                }
                else if (e.Btn.Id == PermissionKeys.DepartmentUpdate)
                {
                    // 为了防止同一个地址
                    DepartmentDetailModel baseModel = model.ToEntity().ToDetailModel();
                    var modifyView = new DepartmentManagementModify(ParentForm, _departmentModels, _allDepartments, _userModels, baseModel, "编辑部门");
                    AntdUI.Modal.open(new Modal.Config(ParentForm, modifyView)
                    {
                        OnOk = ok =>
                        {
                            if (string.IsNullOrEmpty(baseModel.Name))
                            {
                                AntdUI.Message.error(ParentForm, "名称不能为空");
                                return false;
                            }
                            // 目录卡控
                            if (!DetermineTheParent(baseModel, out string message))
                            {
                                AntdUI.Message.error(ParentForm, message);
                                return false;
                            }
                            var baseParentModel = _allDepartments.FirstOrDefault(a => a.Id == model.ParentId);
                            _departmentService.UpdateDepartment(baseModel.ToEntity());
                            AntdUI.Message.success(ParentForm, "修改成功");
                            DoRefresh();
                            return true;
                        }
                    });
                }
                else if (e.Btn.Id == PermissionKeys.DepartmentCreateChild)
                {
                    DepartmentDetailModel baseModel = new DepartmentDetailModel { ParentId = model.Id, ParentName = model.Name };
                    var modifyView = new DepartmentManagementModify(ParentForm, _departmentModels, _allDepartments, _userModels, baseModel, "新增子部门");
                    AntdUI.Modal.open(new Modal.Config(ParentForm, modifyView)
                    {
                        OnOk = ok =>
                        {
                            if (string.IsNullOrEmpty(baseModel.Name))
                            {
                                AntdUI.Message.error(ParentForm, "名称不能为空");
                                return false;
                            }
                            // 目录卡控
                            if (!DetermineTheParent(baseModel, out string message))
                            {
                                AntdUI.Message.error(ParentForm, message);
                                return false;
                            }
                            _departmentService.CreateDepartment(baseModel.ToEntity());
                            AntdUI.Message.success(ParentForm, "新增子菜单成功");
                            DoRefresh();
                            return true;
                        }
                    });
                }
            }
        }

        private bool DetermineTheParent(DepartmentDetailModel baseModel, out string message)
        {
            message = "";
            var baseParentModel = _allDepartments.FirstOrDefault(a => a.Id == baseModel.ParentId);
            //if (baseModel.Type == 0 || baseModel.Type == 1)
            //{
            //    if (baseParentModel != null && baseParentModel.Type != 0)
            //    {
            //        message = "菜单/目录的父级只能是目录";
            //        return false;
            //    }
            //}
            //else if (baseModel.Type == 2)
            //{
            //    if (baseParentModel == null || baseParentModel.Type != 1)
            //    {
            //        message = "按钮的父级只能是菜单";
            //        return false;
            //    }
            //}
            return true;
        }
    }
}
